const ws = require("nodejs-websocket");
const fs = require('fs');
const path = require('path');
const port = 1801;

//参考文档：https://github.com/sitegui/nodejs-websocket#readme
//返回消息
function callbackRes(conn, res, obj) {
    // 检查连接是否有效
    if (!conn || conn.readyState !== conn.OPEN) {
        console.log('无法发送消息 - 连接已关闭');
        return;
    }

    try {
        let messageId = obj.messageId;
        let message = obj.message;
        let fun = obj.func;
        let newRes = {};

        if (typeof res === "function") {
            newRes = res(obj);
        } else {
            newRes = res;
        }

        newRes.messageId = messageId;
        newRes.message = message;
        newRes.func = fun;

        conn.send(JSON.stringify(newRes));
    } catch (e) {
        console.error('发送消息出错:', e);
    }
}

// 递归获取目录下的所有文件
function getFiles(dir, filesList = {}) {
    const files = fs.readdirSync(dir);
    files.forEach(file => {
        const filePath = path.join(dir, file);
        if (fs.statSync(filePath).isDirectory()) {
            getFiles(filePath, filesList); // 递归遍历子目录
        } else {
            filesList[file] = filePath;
        }
    });
    return filesList;
}
const mockFiles = getFiles(path.join(__dirname, 'ws'));

//全部引入
let mockFilesModule = {};
for (let key in mockFiles) {
    let file = mockFiles[key];
    mockFilesModule[key] = require(`${file}`);
}

//推送服务
function pushService(conn) {

    //每秒定时推送
    let filename = 'push.test.js';
    let res = mockFilesModule[filename];

    let intervalId = setInterval(() => {
        if (conn.readyState === conn.OPEN) {
            callbackRes(conn, res, { func: 'push.test' });
        } else {
            // 如果连接关闭，清除定时器
            clearInterval(intervalId);
        }
    }, res.timer);

    //其他推送
}


//创建WS服务
var server = ws.createServer(conn => {
    console.log("New connection", server.connections.length);

    // 监听客户端返回的数据
    conn.on("text", function (str) {
        console.log("onMessage", str);
        //conn.send(JSON.stringify(heart));
        try {
            let obj = JSON.parse(str);
            if (obj.func) {
                let filename = obj.func + '.js';
                let res = mockFilesModule[filename].res;
                callbackRes(conn, res, obj);
            } else {
                let res = {
                    code: "991106",
                    data: null,
                    msg: "没有找到对应的资源,请检查!"
                };
                callbackRes(conn, res, obj);
            }
        } catch (err) {
            console.log(err);
        }
    });

    conn.on("binary", function (inStream) {
        console.log("ws-binary");
    });

    conn.on("close", function (code, reason) {
        console.log(code, "连接关闭");
        console.log(reason);

    });

    conn.on("error", function (err) {
        if (err.code === 'ECONNRESET') {
            console.log('客户端主动断开连接');
        } else {
            console.log(err, "连接报错");
        }
    });

    //推送服务
    pushService(conn);

});

server.listen(port, function () {
    console.log('listening on websocketServer:' + port);
});


